package sidecar

import (
	"encoding/json"
	"regexp"
	"strconv"

	su "lqq/sidecar/utils"
)

type RequestHeader struct {
	TRACEID           string
	REQID             string
	CLIENTID          string
	ClientServiceName string
	StatusCode        int
	ContentType       string
	CallURL           string
	ServiceName       string
	HashStr           string
}

type requestHeaderReadWriter interface {
	read(b []byte) (*RequestHeader, error)
	write(header *RequestHeader) ([]byte, error)
}

func createDefaultRequestHeaderReadWriter() requestHeaderReadWriter {
	return &propRequestHeaderReadWriter{}
}

// 通过json传递头
type jsonRequestHeaderReadWriter struct{}

func (j *jsonRequestHeaderReadWriter) read(headerBytes []byte) (*RequestHeader, error) {
	reqHeader := &RequestHeader{}
	err := json.Unmarshal(headerBytes, reqHeader)
	if err != nil {
		return nil, err
	}
	return reqHeader, nil
}
func (j *jsonRequestHeaderReadWriter) write(header *RequestHeader) ([]byte, error) {
	return json.Marshal(header)
}

// 通过props传递头数据
type propRequestHeaderReadWriter struct{}

func (j *propRequestHeaderReadWriter) read(headerBytes []byte) (*RequestHeader, error) {
	reqHeader := &RequestHeader{}
	confs := su.ReadPropToMap(headerBytes)
	reqHeader.ServiceName = confs["ServiceName"]
	reqHeader.TRACEID = confs["TRACEID"]
	sc := confs["StatusCode"]
	if len(sc) > 0 {
		g := regexp.MustCompile("[0-9]+")
		if g.MatchString(sc) {
			statusCode, err := strconv.Atoi(sc)
			if err == nil {
				reqHeader.StatusCode = statusCode
			}
		}
	}
	reqHeader.CallURL = confs["CallURL"]
	reqHeader.ContentType = confs["ContentType"]
	return reqHeader, nil
}
func (j *propRequestHeaderReadWriter) write(header *RequestHeader) ([]byte, error) {
	return []byte(
		"ServiceName=" + header.ServiceName + "\n" +
			"TRACEID=" + header.TRACEID + "\n" +
			"StatusCode=" + strconv.Itoa(header.StatusCode) + "\n" +
			"CallURL=" + header.CallURL + "\n" +
			"ContentType=" + header.ContentType + "\n"), nil
}
